package cn.hxh.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

/**
 * @Author: HongXiaoHan
 * @Description
 * @Date: 2020/8/19 21:57
 */
public class FileDowloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取下载的资源路径
        FileInputStream in = new FileInputStream("D:\\Documents\\Pictures\\二次元\\8ceaabdd0d174bea1696e940bdde77cc.jpeg");
        //设置响应头
        resp.setHeader("Content-Disposition","attachment;filename="+URLDecoder.decode("Test.jpeg","UTF-8"));
        //获取输出流
        ServletOutputStream outputStream = resp.getOutputStream();
        //设置缓冲区
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = in.read(bytes)) != -1) {
            outputStream.write(bytes,0,len);
        }

        in.close();
        outputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}